package com.example.starter.pubsub.rocketmq;

import cn.hutool.core.util.ObjUtil;
import com.example.starter.pubsub.api.PubCallback;
import com.example.starter.pubsub.api.PubResult;
import com.example.starter.pubsub.api.PubTemplate;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

/**
 * @author 王令
 * @since 2023/6/30 10:57
 */
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "com.example.pub-sub", name = "type", havingValue = "rocketmq")
public class RocketmqPubTemplate implements PubTemplate {

    private final RocketMQTemplate rocketMQTemplate;

    @Override
    public PubResult syncSend(String topic, Object message) {
        final SendResult sendResult = rocketMQTemplate.syncSend(topic, message);
        return new RocketmqPubResultAdapter(sendResult);
    }

    @Override
    public void asyncSend(String topic, Object message, PubCallback callback) {
        rocketMQTemplate.asyncSend(topic, message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                if (ObjUtil.isNotNull(callback)) {
                    callback.onSuccess(new RocketmqPubResultAdapter(sendResult));
                }
            }

            @Override
            public void onException(Throwable throwable) {
                if (ObjUtil.isNotNull(callback)) {
                    callback.onFailure(throwable);
                }
            }
        });
    }

    @Override
    public void asyncSend(String topic, Object message) {
        rocketMQTemplate.asyncSend(topic, message, null);
    }
}
